package com.x.xiaoshuo.ui.read;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.futuremind.recyclerviewfastscroll.FastScroller;
import com.futuremind.recyclerviewfastscroll.SectionTitleProvider;
import com.futuremind.recyclerviewfastscroll.viewprovider.DefaultScrollerViewProvider;
import com.x.mvp.appbar.TransAppBarFragment;
import com.x.mvp.base.recycler.PullToRefreshRecyclerActivityView;
import com.x.mvp.base.recycler.RecyclerAdapter;
import com.x.mvp.base.recycler.RecyclerViewHolder;
import com.x.service.entity.BookDetail;
import com.x.service.entity.BookListsBean;
import com.x.service.entity.ChapterList;
import com.x.xiaoshuo.Constant;
import com.x.xiaoshuo.R;
import com.x.xiaoshuo.di.XActivityComponent;
import com.x.xiaoshuo.manager.CacheManager;
import com.x.xiaoshuo.manager.SettingManager;
import com.x.xiaoshuo.ui.appbar.LeftTitleAppBarBuilder;

import java.io.File;
import java.util.List;

import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.x.xiaoshuo.ui.read.ChaptersPresenter.INTENT_BOOKID;
import static com.x.xiaoshuo.ui.read.ChaptersPresenter.INTENT_SCREEN_OR;


public class ChaptersActivity extends PullToRefreshRecyclerActivityView<ChaptersPresenter> {
    LeftTitleAppBarBuilder leftTitleAppBarBuilder;

    String bookId;

    int chapter = 0;

    ChapterAdapter chapterAdapter;

    FastScroller fastScroller;

    TextView text;


    private void bindView(){
        text = findViewById(R.id.text);
        fastScroller = findViewById(R.id.fastscroll);
    }

    public static void startActivity(Context context, BookListsBean bookListsBean) {
        startActivity(context, bookListsBean, 0);
    }

    public static void startActivity(Context context, BookListsBean bookListsBean, int screenOr) {
        context.startActivity(new Intent(context, ChaptersActivity.class)
                .putExtra(INTENT_BOOKID, bookListsBean)
                .putExtra(INTENT_SCREEN_OR, screenOr));
    }

    public static void startActivity(Context context, BookDetail bookDetail) {
        BookListsBean bookListsBean = new BookListsBean();
        bookListsBean._id = bookDetail._id;
        bookListsBean.title = bookDetail.title;
        bookListsBean.author = bookDetail.author;
        bookListsBean.cover = bookDetail.cover;
        bookListsBean.lastChapter = bookDetail.lastChapter;
        bookListsBean.updated = bookDetail.updated;
        bookListsBean.sourceName = bookDetail.sourceName;
        bookListsBean.majorCate = bookDetail.majorCate;
        bookListsBean.minorCate = bookDetail.minorCate;
        bookListsBean.isSerial = bookDetail.isSerial;
        context.startActivity(new Intent(context, ChaptersActivity.class)
                .putExtra(INTENT_BOOKID, bookListsBean));
    }

    @Override
    protected int getPullMode() {
        return PULL_MODE_DISABLED;
    }

    @Override
    protected void injectComponent() {
        bindView();
        ((XActivityComponent) getActivityComponent()).inject(this);
    }

    @Override
    protected int getLayoutId() {
        switch (getIntent().getIntExtra(INTENT_SCREEN_OR, 0)) {
            case Constant.SCREEN_ORIENTATION_PORTRAIT:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            case Constant.SCREEN_ORIENTATION_LANDSCAPE:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            default:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
        }
        return R.layout.chapter_lst;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        leftTitleAppBarBuilder = new LeftTitleAppBarBuilder();
        TransAppBarFragment appBarFragment = leftTitleAppBarBuilder.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).builder();
        leftTitleAppBarBuilder.setRes(R.drawable.icon_directory);
        leftTitleAppBarBuilder.setText("目录");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.appbar_container, appBarFragment)
                .commitAllowingStateLoss();

        fastScroller.setRecyclerView(getRecyclerView());
        XScrollerViewProvider xScrollerViewProvider = new XScrollerViewProvider();
        fastScroller.setViewProvider(xScrollerViewProvider);
        fastScroller.removeView(xScrollerViewProvider.getBubble());

    }

    class XScrollerViewProvider extends DefaultScrollerViewProvider {
        TextView textView;
        View bubble;

        @Override
        public TextView provideBubbleTextView() {
            textView = super.provideBubbleTextView();
            return textView;
        }

        @Override
        public View provideBubbleView(ViewGroup container) {
            bubble = super.provideBubbleView(container);
            return bubble;
        }

        public TextView getTextView() {
            return textView;
        }

        public View getBubble() {
            return bubble;
        }
    }


    public void showBookToc(List<ChapterList.BookChapter> list) {
        int[] pos = SettingManager.getInstance().getReadProgress(bookId);
        chapter = pos[0];
        getAdapter().replaceAll(list);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {

    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this);
    }

    @Override
    protected RecyclerAdapter getAdapter() {
        if (chapterAdapter == null) {
            chapterAdapter = new ChapterAdapter(getRecyclerView());
            chapterAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener<ChapterList.BookChapter>() {
                @Override
                public void onItemClick(View view, ChapterList.BookChapter data, int position) {
                    presenter.gotoRead(position);
                }
            });

        }
        return chapterAdapter;
    }

    class ChapterHolder extends RecyclerViewHolder<ChapterList.BookChapter> {
        ImageView mark;
        TextView title;
        TextView status;

        public ChapterHolder(View itemView) {
            super(itemView);

            status = itemView.findViewById(R.id.status);
            title = itemView.findViewById(R.id.title);
            mark = itemView.findViewById(R.id.mark);
        }

        @Override
        public void bindView(ChapterList.BookChapter data) {

        }

        public void bindView(ChapterList.BookChapter data, int chapter) {
            mark.setVisibility(View.INVISIBLE);
            title.setText(data.title);
            status.setText("");
            File file = CacheManager.getInstance().getChapterFile(bookId, chapter);
            if (file != null) {
                status.setText("已缓存");
            }

            if (ChaptersActivity.this.chapter == 0) {
                if (0 == chapter) {
                    mark.setVisibility(View.VISIBLE);
                }
            } else {
                if ((ChaptersActivity.this.chapter - 1) == chapter) {
                    mark.setVisibility(View.VISIBLE);
                }
            }


        }
    }

    class ChapterAdapter extends RecyclerAdapter<ChapterList.BookChapter, ChapterHolder> implements SectionTitleProvider {

        public ChapterAdapter(RecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        protected int getItemLayoutID(int viewType) {
            return R.layout.item_chapter;
        }

        @Override
        protected ChapterHolder createItemViewHolder(View itemView, int viewType) {
            return new ChapterHolder(itemView);
        }

        @Override
        protected int getViewType(int position) {
            return 0;
        }

        @Override
        protected void onBindItemViewHolder(ChapterHolder holder, int position, int index, boolean isScrolling) {
            holder.bindView(getData().get(position), index);
        }

        @Override
        public String getSectionTitle(int position) {
            text.clearAnimation();
            text.setText(getData().get(position).title);
            text.setVisibility(View.VISIBLE);
            startAim();
            return null;
        }
    }

    void startAim() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.8f, 0);//初始化操作，参数传入0和1，即由透明度0变化到透明度为1
        text.startAnimation(alphaAnimation);//开始动画
        alphaAnimation.setFillAfter(true);//动画结束后保持状态
        alphaAnimation.setDuration(1000);//动画持续时间，单位为毫秒
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                text.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }
}
